﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace TaskClient5.Web
{
    [DataContract]
    public class UserInfo
    {
        [DataMember]
        public string Id { get; set; }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public string Email { get; set; }

        [DataMember]
        public string Phone { get; set; }

        private static List<UserInfo> _list = new List<UserInfo>
        {
            new UserInfo { Id = Guid.NewGuid().ToString(), Email = "123@123.com", FirstName = "zhang", LastName = "weiwen", Phone = "110" },
            new UserInfo { Id = Guid.NewGuid().ToString(), Email = "123@123.com", FirstName = "Lee", LastName = "tom", Phone = "111" },
            new UserInfo { Id = Guid.NewGuid().ToString(), Email = "124@123.com", FirstName = "Mai", LastName = "Foo", Phone = "112" },
            new UserInfo { Id = Guid.NewGuid().ToString(), Email = "125@123.com", FirstName = "Xia", LastName = "yuyi", Phone = "113" },
            new UserInfo { Id = Guid.NewGuid().ToString(), Email = "126@123.com", FirstName = "Xie", LastName = "bar", Phone = "114" },
        };

        public static UserInfo Create(UserInfo user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            user.Id = Guid.NewGuid().ToString();
            _list.Add(user);
            return user;
        }

        public static void Update(UserInfo user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            var userToUpdate = _list.FirstOrDefault(u => u.Id == user.Id);
            if (userToUpdate == null)
                throw new ArgumentException(string.Format("Id為{0}的用戶不存在", user.Id), "user");

            _list.Remove(user);
            _list.Add(user);
        }

        public static void Delete(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                throw new ArgumentNullException("id");

            var userToDelete = _list.FirstOrDefault(u => u.Id == id);
            if (userToDelete == null)
                throw new ArgumentException(string.Format("Id為{0}的用戶不存在", id), "id");

            _list.Remove(userToDelete);
        }

        public static List<UserInfo> All()
        {
            return _list;
        }

        public static UserInfo GetById(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                throw new ArgumentNullException("id");

            return _list.FirstOrDefault(u => u.Id == id);
        }
    }
}